﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Linq;
namespace cssColorList
{
    public partial class Form1 : Form
    {
        public Form1() {
            InitializeComponent();
        }

        private void btnRefresh_Click(object sender, EventArgs e) {
            List<String> colours = new List<String>();
            //[\n]*([^{]*){[^#]*(#[\d\w]*)[ ;][^}]*}
            Regex regex = new Regex(@"(#[\d\w]*)[ ;]");//color:[ ]*(#[\d\w]*)
            String fileLoc = txtDirectory.Text;
            if (fileLoc.Substring(fileLoc.Length - 1) != "\\") {
                fileLoc += "\\";
            }
            
            foreach (String f in Directory.GetFiles(fileLoc, "*.css"))
            {
                String fileName = f.Substring(0, f.LastIndexOf("."));
                String sFile = File.ReadAllText(fileName + ".css");

                pnlColors.Controls.Clear();
                MatchCollection col = regex.Matches(sFile);
                foreach (Match m in col)
                {
                    String color = m.Groups[1].Value.ToLower();
                    try
                    {
                        System.Drawing.ColorTranslator.FromHtml(color);
                        if (!colours.Contains(color)) {
                            colours.Add(color);
                        }                        
                    }catch(Exception ex){}
                }
            }
            colours.Sort(new ColorSorter());
            foreach (String s in colours) {
                CssColor ctl = new CssColor(s,fileLoc);
                pnlColors.Controls.Add(ctl);
            }
                
        }
       
    }
    public class ColorSorter : IComparer<String>
    {
        public int Compare(string x, string y)
        {
            Color xColor = System.Drawing.ColorTranslator.FromHtml(x);
            Color yColor = System.Drawing.ColorTranslator.FromHtml(y);

            if (xColor.GetHue() == yColor.GetHue())
            {
                return xColor.GetBrightness().CompareTo(yColor.GetBrightness());
            }else
            {
                return xColor.GetHue().CompareTo(yColor.GetHue());                    
            }
            
        }
    }

}
